//
//  YREmoticons.swift
//  表情键盘
//
//  Created by cyr on 15/10/21.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

/// 表情包模型
class YREmoticonPackage: NSObject {
    /// 目录名
    var id: String
    /// 表情数组
    var emoticons: [YREmoticons]?
    /// 分组名
    var groupName: String = ""
    
    
    init(id: String, groupName: String = "") {
        self.id = id
        self.groupName = groupName
    }
    
    /**
    添加最近使用的表情
    */
    class func addFavorate(emoticon:YREmoticons) {
        var ems = package[0].emoticons
        
        ems?.removeLast()
        emoticon.times++
        
        let contains = ems!.contains(emoticon)
        
        if !contains {
            ems!.append(emoticon)
        }
        
        ems = ems!.sort({ (e1, e2) -> Bool in
            return e1.times > e2.times
        })
        if !contains {
            
            ems?.removeLast()
        }
        
        ems?.append(YREmoticons(remove: true))
        
        package[0].emoticons = ems
        
     }
    
     
    /**
    加载所有的表情包
    */
    static let package = YREmoticonPackage.loadPackage()
    private class func loadPackage() -> [YREmoticonPackage] {
        /// 表情包路径
        let path = bundlePath.stringByAppendingString("/"+"emoticons.plist")
        
        let dict = NSDictionary(contentsOfFile: path)!
        let array = dict["packages"] as! [[String: AnyObject]]
        
        // 遍历数组
        var arrayM = [YREmoticonPackage]()
        
        // !!! - 插入最近表情包(追加空表情－在界面上占位)
        let package = YREmoticonPackage(id: "", groupName: "最近").appendEmptyEmotions()
        arrayM.append(package)
        
        for d in array {
            
            let id = d["id"] as! String
            let package = YREmoticonPackage(id: id).loadEmoticons().appendEmptyEmotions()
            
            arrayM.append(package)
        }
        
         return arrayM
    }
    
    /**
    加载当前对象对应的表情数组
    */
    private func loadEmoticons() -> Self {
        
        let path = YREmoticonPackage.bundlePath.stringByAppendingString("/"+id).stringByAppendingString("/info.plist")
        
        let dict = NSDictionary(contentsOfFile: path)!
        
        groupName = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String: String]]
        
        emoticons = [YREmoticons]()
        var index = 0
        for d in array {
            // 将表情包的 id 传递给 表情，方便拼接路径
            emoticons?.append(YREmoticons(id: id, dict: d))
            
            index++
            // 插入删除表情
            if index == 20 {
                emoticons?.append(YREmoticons(remove: true))
                index = 0
            }
        }
        
         return self
    }
    /// 在表情数组中追加空白表情 - 如果最后一页不是 21 个表情，追加空白表情，并且最后一个放删除按钮
   private func appendEmptyEmotions() -> Self {
        
        // 判断表情数组是否存在
        if emoticons == nil {   // 最近分组
            emoticons = [YREmoticons]()
        }
        
        // 判断是否整页
        let count = emoticons!.count % 21
        
        print("已经有 \(count) 个表情")
        
        // count == 0 表示整页不需要追加，同时如果没有任何表情，就追加一个空页
        if count > 0 || emoticons!.count == 0 {
            for _ in count..<20 {
                emoticons?.append(YREmoticons(remove: false))
            }
            // 最末尾追加一个删除按钮
            emoticons?.append(YREmoticons(remove: true))
        }
        return self
    }
    

    
    /// 表情包的路径
   private static let bundlePath = NSBundle.mainBundle().bundlePath.stringByAppendingString("/" + "Emoticons.bundle")
    

    
    
    override var description: String {
        return "\(id)\(groupName)\(emoticons)"
    }
}




class YREmoticons: NSObject {
    /// 表情目录
    var id: String?
 /// 发送给服务器的表情文字
    var chs: String?
 /// 本地显示的图片文件名
    var png: String?
 /// emoji 的代码
    var code: String? {
        didSet {
            let scanner = NSScanner(string: code!)
            
            var value: UInt32 = 0
           scanner.scanHexInt(&value)
            
            emoji = String(Character(UnicodeScalar(value)))
            
        }
    }
    /// 图片完整路径
    var imagePath: String {
        if chs == nil {
            return ""
        }
        
        return YREmoticonPackage.bundlePath.stringByAppendingString("/" + id!).stringByAppendingString("/" + png!)
    }
    
    /// emoji 字符串
    var emoji: String?
    /// 删除表情标记
    var removeEmoticon = false
    
    var times = 0
    
    init(remove: Bool) {
        removeEmoticon = remove
    }

    
    
    init(id: String, dict: [String: String]) {
        self.id = id
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}

    override var description: String {
        return"\(chs)\(png)\(code)"
    }
}
